package common

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	log "github.com/sirupsen/logrus"
	"os"
	"time"
)
type MyCustomClaims struct {
	User string `json:"user"`
	ID int `json:"id"`
	jwt.StandardClaims
}
func GetJWTToken(user string,ID int)(string,error){
	key := []byte(os.Getenv("JWT_KEY"))
	claim := MyCustomClaims{
		User: user,
		ID: ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour *time.Duration(7)).Unix(),
			Issuer: JWT_ISSUER,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,claim)

	ss,err := token.SignedString(key)
	if err != nil {
		log.Errorf("Fail to sign JWT,err: %v",err)
		return "",err
	}
	return ss,nil
}
func ParseJWTToken(tokenString string)(*MyCustomClaims,error){
	res,err := jwt.ParseWithClaims(tokenString,&MyCustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		if _,ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil ,fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(os.Getenv("JWT_KEY")),nil
	})
	if err !=nil {
		log.Errorf("Fail to get token,err :%v",err)
		return nil ,err
	}
	if claims,ok := res.Claims.(*MyCustomClaims);ok && res.Valid {
		return claims,nil
	}
	return nil,errors.New("fail to get MyCustomClaims")
}